<style type="text/css">
    #mapeditor {
        height: 600px;
        width: 600px;
        border: 1px solid black;
        display:inline-block;
    }
    #gui {
        width: 200px;
        padding: 1em;
        vertical-align: top;
        display:inline-block;
    }
    #controls {
        width: 512px;
    }
    #controlToggle {
        padding-left: 1em;
    }
    #controlToggle li {
        list-style: none;
    }
</style>
<div id="mapeditor"></div>
<div id="gui">
    <div>File Name : <span id="fileNameSpan"></span></div>
    <div>
        <button onclick="javascript:openSaveDialog();">Save</button>
        <button onclick="javascript:openLoadDialog();">Load</button>
        <button onclick="javascript:openDownloadDialog();">Download</button>
    </div>
    <div>
        <textarea id="wkt" cols="30" rows="8"></textarea>
        <button onclick="javascript:mapToText();">Map -> Text</button>
        <button onclick="javascript:textToMap($('#baseprojectionhidden').val());">Text -> Map</button>
    </div>

    <hr />

    <div id="controls">
        <ul id="controlToggle">
            <li>
                <input type="radio" name="type" value="none" id="noneToggle"
                       onclick="toggleControl(this);" checked="checked" />
                <label for="noneToggle">navigate</label>
            </li>
            <li style="display: none;">
                <input type="radio" name="type" value="point" id="pointToggle" onclick="toggleControl(this);" />
                <label for="pointToggle">draw point</label>
            </li>
            <li style="display: none;">
                <input type="radio" name="type" value="line" id="lineToggle" onclick="toggleControl(this);" />
                <label for="lineToggle">draw line</label>
            </li>
            <li>
                <input type="radio" name="type" value="polygon" id="polygonToggle" onclick="toggleControl(this);" />
                <label for="polygonToggle">draw polygon</label>
            </li>
            <li>
                <input type="radio" name="type" value="regular" id="regularToggle" onclick="toggleControl(this);" />
                <label for="regularToggle">draw regular polygon</label>
                <label for="sides"> - sides</label>
                <input id="sides" type="text" size="2" maxlength="2"
                       name="sides" value="5" onchange="update()" />
                <ul>
                    <li>
                        <input id="irregular" type="checkbox"
                               name="irregular" onchange="update()" />
                        <label for="irregular">irregular</label>
                    </li>
                </ul>
            </li>
            <li>
                <input type="radio" name="type" value="modify" id="modifyToggle"
                       onclick="toggleControl(this);" />
                <label for="modifyToggle">modify feature</label>
                <ul>
                    <li>
                        <input id="createVertices" type="checkbox" checked
                               name="createVertices" onchange="update()" />
                        <label for="createVertices">allow vertices creation</label>
                    </li>
                    <li>
                        <input id="rotate" type="checkbox"
                               name="rotate" onchange="update()" />
                        <label for="rotate">allow rotation</label>
                    </li>
                    <li>
                        <input id="resize" type="checkbox"
                               name="resize" onchange="update()" />
                        <label for="resize">allow resizing</label>
                        (<input id="keepAspectRatio" type="checkbox"
                                name="keepAspectRatio" onchange="update()" checked="checked" />
                        <label for="keepAspectRatio">keep aspect ratio</label>)
                    </li>
                    <li>
                        <input id="drag" type="checkbox"
                               name="drag" onchange="update()" />
                        <label for="drag">allow dragging</label>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</div>
<div id="loadDialog" style="display: none;">
    <div>Select file to load :</div>
    <div id="fileList"></div>
</div>

<div id="DownloadDialog" style="display: none;">
    <div>Select file to load :</div>
    <div id="fileDLList"></div>
</div>
<div id="saveDialog" style="display: none;">
    <div>File Name : <input type="text" id="fileName" /></div>
</div>
<input type="hidden" id="baseprojectionhidden" value="EPSG:4326" />

<script type="text/javascript">
            var map, wkt, curFile, controls;

            jQuery(document).ready(function() {
                $("#loadDialog").dialog({
                    modal: true,
                    autoOpen: false,
                    open: function(event, ui) {
                        updateFileList();
                    }
                });
                $("#DownloadDialog").dialog({
                    modal: true,
                    autoOpen: false,
                    open: function(event, ui) {
                        updateDLFileList();
                    }
                });
                $("#saveDialog").dialog({
                    modal: true,
                    autoOpen: false,
                    open: function(event, ui) {
                        $("#fileName").val(curFile);
                    },
                    buttons: [
                        {text: "Save", click: function() {
                                save($("#fileName").val());
                            }}
                    ]
                });
                init();
            });
            function save(fileName) {
                $("#saveDialog").dialog("close");
                mapToText();
                jQuery.ajax("<?php echo site_url("mapeditor/save"); ?>", {
                    async: false,
                    method: "POST",
                    data: {
                        fileName: fileName,
                        wkt: $("#wkt").val()
                    }
                }).done(function(response) {
                    curFile = response;
                    $("#fileNameSpan").text(response);
                });
            }
            function load(fileName) {
                jQuery.ajax("<?php echo site_url("mapeditor/loadFile"); ?>/" + fileName, {
                    async: false
                }).done(function(response) {
                    $("#wkt").val(response);
                    textToMap($("#baseprojectionhidden").val());
                    //EPSG:900913
                    curFile = fileName;
                    $("#fileNameSpan").text(curFile);
                });
            }
            function openSaveDialog() {
                $("#saveDialog").dialog("open");
            }
            function openLoadDialog() {
                $("#loadDialog").dialog("open");
            }

            function openDownloadDialog() {
                $("#DownloadDialog").dialog("open");
            }
            function mapToText() {
                try {
                    $("#wkt").val(getCurWKT($("#baseprojectionhidden").val()));
                } catch (err) {
                    alert("Error, please reload page");
                }
            }
            function textToMap(textProjection) {
                try {
                    var edLayer = map.getLayersByName("Editor")[0];
                    edLayer.removeAllFeatures();
                    var wkts = $("#wkt").val().split(";");
                    var bounds;
                    for (var i = 0; i < wkts.length; i++) {
                        var gtype = wkts[i].split("(")[0];
                        if ((gtype === "POLYGON") || (gtype === "MULTIPOLYGON")) {
                            var feature = wkt.read(wkts[i]);
                            if (textProjection) {
                                var geometry = feature.geometry.clone();
                                geometry.transform(new OpenLayers.Projection(textProjection), map.projection);
                                feature.geometry = geometry;
                            }
                            edLayer.addFeatures(feature);
                            if (!bounds) {
                                bounds = feature.geometry.getBounds();
                            } else {
                                bounds.extend(feature.geometry.getBounds());
                            }
                        }
                    }
                    if (bounds) {
                        map.zoomToExtent(bounds);
                    }
                } catch (err) {
                    alert("Error, please reload page");
                }
            }

            function getCurWKT(textProjection) {
                var edLayer = map.getLayersByName("Editor")[0];
                var features = edLayer.features;
                var ftext = "";
                for (var i = 0; i < features.length; i++) {
                    var feature = features[i].clone();
                    if (textProjection) {
                        var geometry = feature.geometry.clone();
                        geometry.transform(map.projection, new OpenLayers.Projection(textProjection));
                        feature.geometry = geometry;
                    }
                    var wekate = wkt.write(feature);
                    var gtype = wekate.split("(")[0];
                    if ((gtype === "POLYGON") || (gtype === "MULTIPOLYGON")) {
                        ftext += (wekate);
                        if (i < (features.length - 1)) {
                            ftext += ";";
                        }
                    }
                }
                return ftext;
            }

            function updateFileList() {
                jQuery.ajax("<?php echo site_url("mapeditor/getFiles"); ?>", {
                }).done(function(response) {
                    var files = eval(response);
                    $("#fileList").html("").append("<ul>");
                    for (var i = 0; i < files.length; i++) {
                        $("#fileList ul").append("<li><a href='javascript:void(0);' onclick='javascript:load(\"" + files[i] + "\"); $(\"#loadDialog\").dialog(\"close\"); return false;'>" + files[i] + "</a></li>");
                    }
                });
            }

            function updateDLFileList() {
                jQuery.ajax("<?php echo site_url("mapeditor/getFiles"); ?>", {
                }).done(function(response) {
                    var files = eval(response);
                    $("#fileDLList").html("").append("<ul>");
                    for (var i = 0; i < files.length; i++) {
                        $("#fileDLList ul").append("<li><a href='javascript:void(0);' onclick='javascript:window.open(\"<?php echo res_url("vectors"); ?>/" + files[i] + "\"); $(\"#DownloadDialog\").dialog(\"close\"); return false;'>" + files[i] + "</a></li>");
                    }
                });
            }

            ///////
            function init() {
                map = createMapExplorer("mapeditor");
                map.setCenter(new OpenLayers.LonLat(118, 0).transform(
                        map.displayProjection,
                        map.projection), 4);

                OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';
                var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
                renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
                var layer_editor = new OpenLayers.Layer.Vector("Editor", {
                    renderers: renderer
                });

                var layer_gmap_street = new OpenLayers.Layer.Google("Google Map", {
                    sphericalMercator: true,
                    type: google.maps.MapTypeId.STREET
                });

                map.addLayers([layer_editor, layer_gmap_street]);
                map.addControl(new OpenLayers.Control.LayerSwitcher());
                map.addControl(new OpenLayers.Control.MousePosition());

                wkt = new OpenLayers.Format.WKT();

                controls = {
                    point: new OpenLayers.Control.DrawFeature(layer_editor,
                            OpenLayers.Handler.Point),
                    line: new OpenLayers.Control.DrawFeature(layer_editor,
                            OpenLayers.Handler.Path),
                    polygon: new OpenLayers.Control.DrawFeature(layer_editor,
                            OpenLayers.Handler.Polygon),
                    regular: new OpenLayers.Control.DrawFeature(layer_editor,
                            OpenLayers.Handler.RegularPolygon,
                            {handlerOptions: {sides: 5}}),
                    modify: new OpenLayers.Control.ModifyFeature(layer_editor)
                };

                for (var key in controls) {
                    map.addControl(controls[key]);
                }

                document.getElementById('noneToggle').checked = true;
            }

            function update() {
                controls.modify.mode = OpenLayers.Control.ModifyFeature.RESHAPE;
                var rotate = document.getElementById("rotate").checked;
                if (rotate) {
                    controls.modify.mode |= OpenLayers.Control.ModifyFeature.ROTATE;
                }
                var resize = document.getElementById("resize").checked;
                if (resize) {
                    controls.modify.mode |= OpenLayers.Control.ModifyFeature.RESIZE;
                    var keepAspectRatio = document.getElementById("keepAspectRatio").checked;
                    if (keepAspectRatio) {
                        controls.modify.mode &= ~OpenLayers.Control.ModifyFeature.RESHAPE;
                    }
                }
                var drag = document.getElementById("drag").checked;
                if (drag) {
                    controls.modify.mode |= OpenLayers.Control.ModifyFeature.DRAG;
                }
                if (rotate || drag) {
                    controls.modify.mode &= ~OpenLayers.Control.ModifyFeature.RESHAPE;
                }
                controls.modify.createVertices = document.getElementById("createVertices").checked;
                var sides = parseInt(document.getElementById("sides").value);
                sides = Math.max(3, isNaN(sides) ? 0 : sides);
                controls.regular.handler.sides = sides;
                var irregular = document.getElementById("irregular").checked;
                controls.regular.handler.irregular = irregular;
            }

            function toggleControl(element) {
                for (key in controls) {
                    var control = controls[key];
                    if (element.value == key && element.checked) {
                        control.activate();
                    } else {
                        control.deactivate();
                    }
                }
            }
</script>